import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/user.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/view/drive/drive_vechile_page.dart';
import 'package:yuan_hang_app/views/home/view/drive/preview_attachement.dart';
import 'package:yuan_hang_app/widget/image_picker.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/app_response.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/file_utils.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/w_toast.dart';
import '../../model/trial_drive_model.dart';
import 'package:http_parser/http_parser.dart';
import 'contract_lock_page.dart';

class DriveRegistrationPage extends StatefulWidget {
  final String? clueCustomerName;
  final String? cluePhone;
  final Map? bookInfo;

  const DriveRegistrationPage(
      {super.key, this.clueCustomerName, this.cluePhone, this.bookInfo});

  @override
  BaseState<DriveRegistrationPage> createState() =>
      _DriveRegistrationPageState();
}

class _DriveRegistrationPageState extends BaseState<DriveRegistrationPage> {
  final _formKey = GlobalKey<FormState>();

  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> driveTypeList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveType);
  List<Map> driveMethodList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveMethod);
  List<Map> saleManList = WConstant().salesmanList;

  String licenseNo = "";
  Map driveInfo = {
    "customerName": "",
    "phone": "",
    "driveType": "",
    "driveMethod": "",
    "modelIndex": "",
    "saleMan": "",
    "idNo": "",
    "address": "",
    "driveFrom": "24711001",
    "testDriveAgreement": "",
    "driveVehicle": "",
    "frontPictureList": "",
    "backPictureList": "",
    "isProbe": "10041002",
    "registrationTime":
        DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
    "appointId": ""
  };

  String fileInfo = "";

  String clueCustomerName = "";
  String cluePhone = "";

  //是否是销售顾问, 或者店长
  bool isAdviser = false;
  String saleMan = "";

  String? _driverLicenseFrontImage;
  String? _driverLicenseBackImage;
  Uint8List? imageBytes;

  GlobalKey<LabelItemState>? cardCodeKey;
  GlobalKey<LabelItemState>? addressKey;
  GlobalKey<LabelItemState>? customerNameKey;

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "试驾登记",
        resizeToBottomInset: true,
        child: Column(children: [
          Expanded(
              child: SingleChildScrollView(
                  padding: EdgeInsets.zero, child: _bookDriveItem())),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.px, vertical: 10.px),
            child: GestureDetector(
              onTap: () {
                //必填性校验,调用model的方法
                if (!TrialDriveModel.check(driveInfo)) {
                  return;
                }
                //试驾协议必填
                if (fileInfo == "") {
                  Toast.toast("请签署试驾协议");
                  return;
                }
                driveInfo["description"] = "";
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState?.save();
                  showLoading();
                  HttpUtils()
                      .post(Api.saveTestDriveRegistrationInfo, data: driveInfo)
                      .then((value) {
                    hideLoading();
                    print("当前返回的信息是$value");
                    if (value.resultCode == 200) {
                      Toast.toast("提交成功");
                      RouteHelper.maybePop(context, true);
                    } else {
                      Toast.toast(value.errMsg);
                    }
                  }).catchError((e) {
                    hideLoading();
                  });

                  _printFormData();
                  // 这里可以添加提交表单的逻辑
                }
              },
              child: Container(
                margin:
                    EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "提交",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: WDimens.tsLarge,
                  ),
                ),
              ),
            ),
          ),
        ]));
  }

  @override
  void initState() {
    if (widget.clueCustomerName != null) {
      driveInfo["customerName"] = widget.clueCustomerName;
      clueCustomerName = widget.clueCustomerName!;
    }
    if (widget.cluePhone != null) {
      driveInfo["phone"] = widget.cluePhone;
      cluePhone = widget.cluePhone!;
    }
    if (widget.bookInfo != null) {
      driveInfo["customerName"] = widget.bookInfo!["customerName"];
      clueCustomerName = widget.bookInfo!["customerName"];
      driveInfo["phone"] = widget.bookInfo!["phone"];
      cluePhone = StringUtils.safeGetValue(widget.bookInfo!["phone"]);
      driveInfo["appointId"] = widget.bookInfo!["id"];
      driveInfo["modelId"] = widget.bookInfo!["modelId"];
      if(!StringUtils.isEmpty(widget.bookInfo!["driveSource"])){
        driveInfo["driveFrom"] = widget.bookInfo!["driveSource"];
      }
    }

    // TODO: implement initState
    super.initState();
    addressKey = GlobalKey(debugLabel: "address");
    customerNameKey = GlobalKey(debugLabel: "customerName");
    cardCodeKey = GlobalKey(debugLabel: "idNo");
    User user = WConstant().userInfo;
    isAdviser = user.roleCode == "DZ";
    saleMan = user.employeeName ?? "";
    if (!isAdviser) {
      driveInfo["saleMan"] = user.userId;
    }
    driveInfo["shopId"] = user.shopId;
  }

  Widget _bookDriveItem() {
    return Form(
        key: _formKey,
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                left: 16.px, right: 16.px, bottom: 10.px, top: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.CDFEFFB,
                      offset: Offset(0, 1),
                      blurRadius: 3)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  LabelItem(
                      label: "试驾类型",
                      isMust: true,
                      labelType: LabelType.LIST,
                      onSelected: (index) {
                        setState(() {
                          driveInfo["driveType"] = index;
                        });
                      },
                      dataList: driveTypeList,
                      value: driveInfo["driveType"]),
                  LabelItem(
                    label: "试驾方式",
                    isMust: true,
                    labelType: LabelType.LIST,
                    onSelected: (index) {
                      setState(() {
                        driveInfo["driveMethod"] = index;
                      });
                    },
                    dataList: driveMethodList,
                    value: driveInfo["driveMethod"],
                  ),
                  LabelItem(
                    label: "试驾车型",
                    labelType: LabelType.DROW_DOWN,
                    isModel: true,
                    isMust: true,
                    onSelected: (index) {
                      setState(() {
                        driveInfo["modelId"] = index;
                      });
                    },
                    dataList: modelList,
                    value: driveInfo["modelId"],
                  ),
                  isAdviser
                      ? LabelItem(
                          labelType: LabelType.DROW_DOWN,
                          label: "接待顾问",
                          isMust: true,
                          onSelected: (index) {
                            setState(() {
                              driveInfo["saleMan"] = index; //默认下拉框选中其中一个
                            });
                          },
                          dataList: saleManList,
                        )
                      : LabelItem(
                          isMust: true,
                          label: "接待顾问",
                          value: saleMan,
                        ),
                  LabelItem(
                    key: customerNameKey,
                    labelType: LabelType.INPUT,
                    label: "客户名称",
                    maxLength: 50,
                    isMust: true,
                    onChanged: (text) {
                      setState(() {
                        driveInfo["customerName"] = text;
                      });
                    },
                    value: clueCustomerName ?? driveInfo["customerName"],
                  ),
                  LabelItem(
                    labelType: LabelType.INPUT,
                    textInputType: TextInputType.number,
                    label: "手机号码",
                    maxLength: 11,
                    isMust: true,
                    onChanged: (text) {
                      setState(() {
                        driveInfo["phone"] = text;
                      });
                    },
                    value: cluePhone ?? driveInfo["phone"],
                  ),
                  LabelItem(
                    key: cardCodeKey,
                    labelType: LabelType.INPUT,
                    textInputType: TextInputType.number,
                    label: "证件号码",
                    maxLength: 20,
                    isMust: true,
                    onChanged: (text) {
                      setState(() {
                        driveInfo["idNo"] = text;
                      });
                    },
                    value: driveInfo["idNo"],
                  ),
                  LabelItem(
                    key: addressKey,
                    labelType: LabelType.INPUT,
                    label: "客户地址",
                    isMust: true,
                    maxLength: 50,
                    onChanged: (text) {
                      setState(() {
                        driveInfo["address"] = text;
                      });
                    },
                    value: driveInfo["address"],
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: 15.px, vertical: 10.px),
                    child: Row(
                      children: <Widget>[
                        _driverLicense('驾驶证主页'),
                        SizedBox(
                          width: 20.px,
                        ),
                        _driverLicense('驾驶证副页')
                      ],
                    ),
                  ),
                  WLine(
                    height: 0.5.px,
                  ),
                  // 试驾车辆下拉框
                  LabelItem(
                    label: "试驾车辆",
                    isMust: true,
                    labelType: LabelType.SELECT,
                    onTap: () {
                      showModalBottomSheet(
                        context: context,
                        isScrollControlled: true, // 允许滚动
                        builder: (BuildContext context) {
                          return Container(
                            constraints: BoxConstraints(maxHeight: 500.px),
                            decoration: BoxDecoration(
                                color: WColors.white,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(24.px),
                                    topRight: Radius.circular(24.px))),
                            child: const DriveVechilePage(),
                          );
                        },
                      ).then((driveVechile) {
                        if (driveVechile != null) {
                          driveInfo["driveVehicle"] =
                              driveVechile["licenceNo"] +
                                  "-" +
                                  driveVechile["id"];
                          licenseNo = driveVechile["licenceNo"];
                          setState(() {});
                        }
                      });
                    },
                    value: licenseNo,
                  ),
                  // 试驾协议
                  LabelItem(
                    label: "试驾协议",
                    isMust: true,
                    labelType: LabelType.SELECT,
                    value: StringUtils.isEmpty(driveInfo["testDriveAgreement"])
                        ? "请签署"
                        : "重新签署",
                    isLast: true,
                    onTap: () {
                      if (!TrialDriveModel.check(driveInfo)) {
                        return;
                      }
                      RouteHelper.pushWidget(
                              context, ContractLocckPage(driveInfo: driveInfo))
                          .then((value) {
                        if (value != null) {
                          fileInfo = StringUtils.safeGetValue(value["fileUrl"]);
                          driveInfo["testDriveAgreement"] = value["fileId"];
                        }
                        setState(() {});
                      });
                    },
                  ),
                  Offstage(
                    offstage:
                        StringUtils.isEmpty(driveInfo["testDriveAgreement"]),
                    child: GestureDetector(
                        onTap: () async {
                          if (fileInfo.contains("https")) {
                            String time = DateUtil.formatDate(DateTime.now(),
                                format: "yyyyMMddHHmmss.pdf");
                            File? file = await FileUtils.getAppFile(time);
                            if (file == null) {
                              return;
                            }
                            showLoading();
                            HttpUtils()
                                .downloadFile(fileInfo, file.path)
                                .then((res) {
                              hideLoading();
                              RouteHelper.pushWidget(
                                  context,
                                  PreviewAttachementPage(
                                    url: file.path,
                                  ));
                            }).catchError((e) {
                              hideLoading();
                            });
                          } else {
                            RouteHelper.pushWidget(
                                context, PreviewAttachementPage(url: fileInfo));
                          }
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(vertical: 10.px),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              WText(
                                "查看试驾协议",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: WColors.mainTextColor,
                                    fontSize: WDimens.tsLarge),
                              ),
                              SizedBox(width: 5.px),
                              Image.asset(
                                "images/ic_right.png",
                                color: WColors.CCCCCCC,
                                width: 12.px,
                                height: 12.px,
                              )
                            ],
                          ),
                        )),
                  )
                ])));
  }

  // 用于构建显示图片的Widget
  Widget _driverLicense(String label) {
    var imageFile =
        label == "驾驶证主页" ? _driverLicenseFrontImage : _driverLicenseBackImage;
    return Expanded(
        child: Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            WText(
              "*",
              style:
                  TextStyle(color: WColors.redMain, fontSize: WDimens.tsLabel),
            ),
            WText(
              label,
              style: TextStyle(
                  color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
            ),
          ],
        ),
        SizedBox(
          height: 10.px,
        ),
        GestureDetector(
          onTap: () {
            ///进行判断如果选择了照片就执行showImagePicker
            ImagePicker.showImagePicker(
                context: context,
                count: 1,
                onSelected: (file) {
                  ///校验文件是否选中，如果文件未选中不调用上传接口
                  if (file[0] != null && file[0].length > 0) {
                    showLoading();
                    uploadImage(file[0]).then((value) {
                      hideLoading();
                      String val =
                          value.data["data"]["fileUploadId"].toString();
                      if (value.resultCode == 200) {
                        if (label == "驾驶证主页") {
                          _driverLicenseFrontImage = file[0];
                          driveInfo["frontPictureList"] = val;
                          getDriverInfo();
                        } else {
                          _driverLicenseBackImage = file[0];
                          driveInfo["backPictureList"] = val;
                        }
                        setState(() {});
                      } else {
                        Toast.toast(value.errMsg);
                      }
                    }).catchError((e) {
                      hideLoading();
                    });
                  }
                });
          },
          child: imageFile == null
              ? Image.asset(
                  "images/${label == "驾驶证主页" ? 'driver_front.png' : 'driver_back.png'}",
                  fit: BoxFit.cover,
                  width: SizeUtils.screenW() / 2 - 20.px,
                  height: 100.px,
                )
              : Image.file(
                  File(imageFile),
                  fit: BoxFit.cover,
                  width: SizeUtils.screenW() / 2 - 20.px,
                  height: 100.px,
                ),
        )
      ],
    ));
  }

  void getDriverInfo() {
    showLoading();
    HttpUtils()
        .get("${Api.getDriveCardOcr}/${driveInfo["frontPictureList"]}")
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        Map<String, dynamic> dataMap = jsonDecode(data.data);
        print(dataMap);
        driveInfo["address"] = StringUtils.safeGetValue(dataMap['Address']);
        driveInfo["idNo"] = StringUtils.safeGetValue(dataMap['CardCode']);
        driveInfo["customerName"] = StringUtils.safeGetValue(dataMap['Name']);
        customerNameKey!.currentState
            ?.refreshInput(driveInfo["customerName"] ?? "");
        addressKey!.currentState?.refreshInput(driveInfo["address"] ?? "");
        cardCodeKey!.currentState?.refreshInput(driveInfo["idNo"] ?? "");
      } else {
        Toast.toast(data.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  void _printFormData() {
    print('试驾登记信息是: $driveInfo');
  }

  static Future<AppResponse> uploadImage(filePath) {
    FormData formData = FormData.fromMap({
      'file': MultipartFile.fromFileSync(filePath,
          contentType: MediaType.parse("image/jpeg"))
    });
    return HttpUtils().post(Api.uploadFile2, data: formData).then((onValue) {
      return onValue;
    });
  }
}
